/**
 * @author LKQ
 * @date 2021/12/8 20:38
 * @description 自顶向下
 */
public class Solution {
    public static void main(String[] args) {
        TreeNode leaf9 = new TreeNode(9, null, null);
        TreeNode leaf15 = new TreeNode(15, null, null);
        TreeNode leaf7 = new TreeNode(7, null, null);
        TreeNode leaf20 = new TreeNode(20, leaf15, leaf7);
        TreeNode root = new TreeNode(3, leaf9, leaf20);
        Solution solution = new Solution();
        solution.isBalanced(root);
    }

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }else {
            // 判断左右子树高度是否匹配，并且左子树是否为平衡树 && 右子树是否为平衡树
            return Math.abs(depth(root.left) - depth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
        }

    }

    public int depth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return Math.max(depth(root.left), depth(root.right)) + 1;
    }
}
